package io.kiki.stack.netty.channelManager;


import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
@Getter
public final class ReconnectTask implements Runnable {
    public static final int HEAL_channel_INTERVAL = 1000;

    private final ReconnectManager reconnectManager;
    private long lastConnectTime = -1;

    public ReconnectTask(ReconnectManager reconnectManager) {
        this.reconnectManager = reconnectManager;
    }

    @Override
    public void run() {
        while (reconnectManager.isInited()) {
            long start = -1;
            CreateChannelTask createChannelTask = null;
            try {
                if (this.lastConnectTime < HEAL_channel_INTERVAL) {
                    Thread.sleep(HEAL_channel_INTERVAL);
                }

                try {
                    createChannelTask = reconnectManager.queue.take();
                } catch (InterruptedException e) {
                    // ignore
                }

                if (createChannelTask == null) {
                    continue;
                }

                start = System.currentTimeMillis();
                if (!reconnectManager.canceled.contains(createChannelTask.url)) {
                    createChannelTask.run();
                } else {
                    log.warn("Invalid reconnect request task {}, cancel list size {}", createChannelTask.url, reconnectManager.canceled.size());
                }
                this.lastConnectTime = System.currentTimeMillis() - start;
            } catch (Exception e) {
                if (start != -1) {
                    this.lastConnectTime = System.currentTimeMillis() - start;
                }

                if (createChannelTask != null) {
                    log.warn("reconnect target: {} failed.", createChannelTask.url, e);
                    reconnectManager.queue.add(createChannelTask);
                }
            }
        }
    }
}
